import NavBar from '@/components/NavBar'
import React, { useState } from 'react'
import styles from './index.module.scss'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { login, sendCode } from '@/store/actions/login'
import { Toast } from 'antd-mobile'
export default function Login({ history, location }) {
  const dispatch = useDispatch()

  // 验证码倒计时
  const [time, setTime] = useState(0)

  // 发送验证码
  const onExtraClick = async () => {
    // 倒计时未完成不能点击
    if (time > 0) return
    // 校验手机号
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      // 触发手机号输入框校验
      formik.setTouched({ mobile: true })
      return
    }
    // 操作结果提示
    await dispatch(sendCode(mobile))
    Toast.success('获取验证码成功', 1)
    // 验证码发送成功60s倒计时
    setTime(60)
    let timeId = setInterval(() => {
      setTime((time) => {
        if (time === 1) {
          clearInterval(timeId)
        }
        return time - 1
      })
    }, 1000)
  }

  // 表单校验
  const formik = useFormik({
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },
    // 表单提交触发
    onSubmit: async (values) => {
      await dispatch(login(values))
      Toast.success('登录成功', 1)
      if (location.from) {
        history.replace(location.state.from.pathname)
      } else {
        history.replace('/home')
      }
    },
    // 校验规则
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('手机号不能为空')
        .matches(/^1[3-9]\d{9}$/, '手机号格式不正确'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '验证码为6位'),
    }),
  })

  const {
    values: { mobile, code },
    handleChange,
    handleSubmit,
    handleBlur,
    errors,
    isValid,
  } = formik

  return (
    <div className={styles.root}>
      {/* 顶部导航 */}
      <NavBar>登录</NavBar>
      {/* 登录表单 */}
      <div className="content">
        <h3>短信登录</h3>
        <form onSubmit={handleSubmit}>
          <div className="input-item">
            <Input
              placeholder="请输入手机号"
              value={mobile}
              name="mobile"
              onChange={handleChange}
              autoComplete="off"
              onBlur={handleBlur}
              maxLength={11}
            ></Input>
            {errors.mobile && <div className="validate">{errors.mobile}</div>}
          </div>
          <div className="input-item">
            <Input
              placeholder="请输入验证码"
              extra={time === 0 ? '获取验证码' : time + '秒后可再次发送'}
              autoComplete="off"
              value={code}
              name="code"
              onExtraClick={onExtraClick}
              onChange={handleChange}
              onBlur={handleBlur}
              maxLength={6}
            ></Input>
            {errors.code && <div className="validate">{errors.code}</div>}
          </div>
          <button
            type="submit"
            className={classNames('login-btn', { disabled: !isValid })}
            disabled={!isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
